package com.atguigu.gulimall.auth.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.common.constant.AuthServerConstant;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.MemberRespVo;
import com.atguigu.gulimall.auth.feign.MemberFeignService;
import com.atguigu.gulimall.auth.utils.HttpUtils;
import com.atguigu.gulimall.auth.vo.SocialUser;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * @author xyouzi
 * @date 2022/7/30 10:52
 */
@Controller
public class Oauth2Controller {

    @Autowired
    MemberFeignService memberFeignService;

    @GetMapping("/oauth2/gitee/success")
    public String gitee(@RequestParam("code")String code, HttpSession session) throws Exception {
        Map<String, String> map = new HashMap<>();
        map.put("grant_type","authorization_code");
        map.put("code",code);
        map.put("client_id","835e891ece6fee1c2e573d03e03c7808b2a88370415e1b74c67b9de9eff82963");
        map.put("redirect_uri","http://auth.gulimall.com/oauth2/gitee/success");
        map.put("client_secret","ca98252bf0b0596653b44e187949967f75063cca8bcf49d62280b29cac1b5614");
        HttpResponse post = HttpUtils.doPost("https://gitee.com", "/oauth/token", "post", null, null, map);
        if (post.getStatusLine().getStatusCode()==200) {
            String json = EntityUtils.toString(post.getEntity());
            SocialUser socialUser = JSON.parseObject(json, SocialUser.class);
//            String uid = String.format("%04d", new Random().nextInt(9999));
//            System.out.println(socialUser);
            socialUser.setId(socialUser.getId());
            // 调用远程社交登录接口
            R oauthlogin = memberFeignService.oauthlogin(socialUser);
            if (oauthlogin.getCode() == 0) {
                Object data = oauthlogin.get("data");
                String userInfo = JSONObject.toJSONString(data);
                MemberRespVo memberRespVo = JSONObject.parseObject(userInfo, MemberRespVo.class);
//                System.out.println(memberRespVo);
                session.setAttribute(AuthServerConstant.LOGIN_USER ,memberRespVo);
                return "redirect:http://gulimall.com";
            } else {
                return "redirect:http://auth.gulimall.com/login.html";
            }
        } else {
            return "redirect:http://auth.gulimall.com/login.html";
        }
    }
}
